<template>
  <el-dialog
    :visible.sync="isShowImageDialog"
    @closed="clearImg"
  >
    <el-carousel height="610px" ref="carousel" indicator-position="none" @click.native="downloadFiles">
      <el-carousel-item v-for="src in imgs" :key="src.index" class="carousel-item">
        <img v-if="isImage(src)" :src="src" class="carousel-img"/>
        <img v-else src="~@/assets/img/file.png" alt="点击下载"
             style="display: block;margin:200px auto;cursor: pointer"/>
      </el-carousel-item>
    </el-carousel>
  </el-dialog>
</template>

<script>
export default {
  name: 'ImgPreview',
  data() {
    return {
      imgs: '',
      isShowImageDialog: false
    }
  },
  methods: {
    clearImg() {
      this.imgs = null
    },
    isImage(url) {
      // 获取最后一个.的位置
      let index = url.lastIndexOf('.')
      // 获取后缀
      let ext = url.substr(index + 1)
      if (['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1) {
        return true
      }
      return false
    },
    downloadFiles() {
      let activeIndex = this.$refs.carousel.activeIndex
      let url = this.imgs[activeIndex]
      if (!this.isImage(url)) {
        // 获取最后一个.的位置
        let index = url.lastIndexOf('.')
        // 获取后缀
        let ext = url.substr(index + 1)
        const elink = document.createElement('a')
        elink.download = '附件.' + ext
        elink.style.display = 'none'
        // const content = res.data;
        // const blob = new Blob([content]);
        // elink.href = URL.createObjectURL(blob)
        elink.href = url
        elink.target = '_blank'
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      }
    }
  }
}
</script>

<style scoped>
.carousel-item {
  width: 100%;
  height: 100%;
  background: white;
  display: flex;
  justify-content: center;
}

.carousel-img {
  max-width: 100%;
  max-height: 100%;
}
</style>
